package com.zqwzd.util;

import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 保存图片、文件的服务，其实只是单纯的处理字符流信息
 * @author BOBO
 *
 */
public class FileService {
	public static final int BUF_SIZE 		= 1024 * 100;
	public static final String FILE_SEP 	= System.getProperties().getProperty("file.separator");
	public static final String FILE_PATH 	= System.getProperties().getProperty("zqwzd.root") + "images" + FILE_SEP;
	
	/**
	 * 保存文件到FILE_PATH目录下
	 * 
	 * @param file
	 * @param fileName
	 * @return
	 */
	public static boolean saveFile(File file, String fileName){
		FileInputStream fis = null;
		FileOutputStream fos = null;
		try { 
			if (!file.getParentFile().exists()) {
				file.getParentFile().mkdirs();
			}
			fis = new FileInputStream(file);
			fos = new FileOutputStream(FILE_PATH + fileName);
			byte[] buffer = new byte[1024];
			int size = 0;
			while ((size = fis.read(buffer)) != -1) {
				fos.write(buffer, 0, size);
			}
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			e.printStackTrace();
			return false;
		}finally{
			close(fis);
			close(fos);
		}
	}
	
	/**
	 * 关闭流.
	 * 
	 * @param os
	 */
	public static void close(Closeable closeable) {
		if (closeable != null) {
			try {
				closeable.close();
			} catch (Exception e) {}
		}
	}
	
	/**
	 * 删除文件
	 * 
	 * @param file
	 * @return
	 */
	public static boolean deleteFile(File file) {
		return file.delete();
	}
}
